package com.ken.rxhttp.http_api_impl

import android.annotation.SuppressLint
import com.google.gson.JsonSyntaxException
import com.ken.base_http_library.news.NewsResponse
import com.ken.rxhttp.api.ApiService
import com.ken.rxhttp.callback.OnDesCallback
import com.ken.rxhttp.news.JuHeNewBaseResponse
import com.rxlife.coroutine.RxLifeScope
import kotlinx.coroutines.TimeoutCancellationException
import rxhttp.toClass
import rxhttp.toOkResponse
import rxhttp.wrapper.annotation.DefaultDomain
import rxhttp.wrapper.exception.HttpStatusCodeException
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException


/**
 * @author by ken
 * Blog:
 * Date:2020/5/12
 * Description:
 */
object ApiServiceImpl : ApiService {
    @DefaultDomain //设置为默认域名
    const val baseUrl = "http://v.juhe.cn/"

    var rxLifeScope = RxLifeScope()

    init {


    }

    suspend fun impl(): NewsResponse? {
        var news: NewsResponse? = null


        return news
    }


    private val Throwable.code: Int
        get() {
            val errorCode = when (this) {
                is HttpStatusCodeException -> this.statusCode //Http状态码异常
                is ParseException -> this.errorCode     //业务code异常
                else -> "-1"
            }
            return try {
                errorCode.toInt()
            } catch (e: Exception) {
                println(e.message)
                -1
            }
        }

    private val Throwable.msg: String
        get() {
            return if (this is UnknownHostException) { //网络异常
                "当前无网络，请检查你的网络设置"
            } else if (
                this is SocketTimeoutException  //okhttp全局设置超时
                || this is TimeoutException     //rxjava中的timeout方法超时
                || this is TimeoutCancellationException  //协程超时
            ) {
                "连接超时,请稍后再试"
            } else if (this is ConnectException) {
                "网络不给力，请稍候重试！"
            } else if (this is HttpStatusCodeException) {               //请求失败异常
                "Http状态码异常"
            } else if (this is JsonSyntaxException) {  //请求成功，但Json语法异常,导致解析失败
                "数据解析失败,请检查数据是否正确"
            } else if (this is ParseException) {       // ParseException异常表明请求成功，但是数据不正确
                this.message ?: errorCode   //msg为空，显示code
            } else {
                "请求失败，请稍后再试"
            }
        }

    override fun getNews(key: String, type: String, callback: OnDesCallback<NewsResponse>) {
        println("${key}...${type}...")
        rxLifeScope.launch({
            callback.onSuccess(
                res = RxHttp.get("toutiao/index")  //第一步, 通过get、postXxx、putXxx等方法，确定请求类型
                    .add("key", key)
                    .add("type", type)
                    .toResponse<NewsResponse>()//第二步, 通过asXxx系列方法，确定返回数据类型
                    .await()
            )
        }, {
            it.code
            it.msg
            callback.onError(code = it.code, msg = it.msg)

        })
    }

}

